from django.http import JsonResponse
from django.views.generic import View
from utils.encryptionAndDecryptionUtil import get_useraccount_from_request
from control.models.User import User
from ..serializers.langInfoSerializer import LangCreateSerializer
from ..serializers.langListSerializer import LangListSerializer
import json
from ..utils.literUtils import handle_serializer_error
from ..models.GlobalTables import Language
import traceback
 

class LanguageView(View):
    def post(self, request):
        '''
        传入的language_data格式如下:
        {
            "name": "",
            "zh_name": "",
        }
        '''
        res = {"code": 400, "message": "", "data": None}
        try:
            user_name = get_useraccount_from_request(request=request)
            u = User.objects.filter(user_account=user_name)[0]
            # print(request.body)
            data = json.loads(request.body)
            add_serializer = LangCreateSerializer(data=data)
            data_valid = add_serializer.is_valid()
            if not data_valid:
                serial_errors = handle_serializer_error(
                    errors=add_serializer.errors)
                res["code"] = 400
                res["message"] = "参数错误：\n" + serial_errors
                return JsonResponse(res)
            data = add_serializer.validated_data
            data["creator"] = u
            data["last_editor"] = u
            Language.objects.create(**data)
            res["code"] = 200
            res["message"] = "新建成功"
            res["data"] = None
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            languages = Language.objects.all().order_by('create_date')
            total_count = languages.count()
            res_data = {}
            res_data["total_count"] = total_count
            lang_list_serializer = LangListSerializer(
                languages, many=True)
            res_data["options"] = lang_list_serializer.data
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = res_data
            return JsonResponse(res)
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)